import pandas as pd
import os
from lxml import etree
from database_manager import SQLiteDBManager
import configparser

# 读取 ini 配置文件键的函数
def read_ini_key(ini_path, section='Classification', key='CurrentClassification'):
    try:
        if not os.path.exists(ini_path):
            print(f"文件不存在: {ini_path}")
            return None
        target_section = f'[{section}]'
        with open(ini_path, 'r', encoding='utf-8') as file:
            in_target_section = False
            for line in file:
                line = line.strip()
                if line == target_section:
                    in_target_section = True
                elif line.startswith('[') and line.endswith(']'):
                    if in_target_section:
                        break
                    continue
                elif in_target_section:
                    equal_index = line.find('=')
                    if equal_index != -1:
                        current_key = line[:equal_index].strip()
                        if current_key == key:
                            return line[equal_index + 1:].strip()
        print(f"未找到指定的 section: {section} 或 key: {key}")
        return None
    except Exception as e:
        print(f"读取文件时出错: {e}")
        return None

def get_xml_data(xml_path, xpathvalue):
    try:
        # 检查文件是否存在
        if not os.path.exists(xml_path):
            print(f"文件不存在: {xml_path}")
            return []
        tree = etree.parse(xml_path)
        return tree.xpath(xpathvalue)
    except Exception as e:
        print(f"数据获取失败：{e}")
        return []

def update_database(db_manager, id_value, size,active_line_grade, enabled, ip, grade_path):
    if enabled is None or enabled == 0:
        update_query = f"UPDATE ip_config SET active_line_grade = '分档未更新' WHERE id = {id_value}"
        db_manager.execute_query(update_query)
        return
    treepath = r"\\" + ip + grade_path
    if size =="整片":
        xml_filename=None
        xml_filename = get_xml_data(treepath, r"//FileName/text()")
        if not xml_filename:
            update_query = f"UPDATE ip_config SET active_line_grade = '分档未更新' WHERE id = {id_value}"
            rows_affected = db_manager.execute_query(update_query)
        elif xml_filename[0] != active_line_grade:
            try:
                update_query = f"UPDATE ip_config SET active_line_grade = '{xml_filename[0]}' WHERE id = {id_value}"
                rows_affected = db_manager.execute_query(update_query)
            except Exception as e:
                print(f"数据库更新异常信息: {e}")
    elif size =="半片":
        ini_filename=None
##        treepath=r'\\10.49.58.40\Info\Recipe\HEHighRsh.recipe'
        treepath = r"\\" + ip + grade_path
        ini_filename=read_ini_key(ini_path=treepath, section='Classification', key='CurrentClassification')
        print(ini_filename)
        if not ini_filename:
            update_query = f"UPDATE ip_config SET active_line_grade = '分档未更新' WHERE id = {id_value}"
            rows_affected = db_manager.execute_query(update_query)
        elif ini_filename != active_line_grade:
            try:
                update_query = f"UPDATE ip_config SET active_line_grade = '{ini_filename}' WHERE id = {id_value}"
                rows_affected = db_manager.execute_query(update_query)
            except Exception as e:
                print(f"数据库更新异常信息: {e}")
    else:
        pass
    
def main():
    # 获取当前文件所在目录的上一个目录
    # current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    # # 构建数据库文件的路径
    # db_path = os.path.join(current_dir, 'database', 'test.db')
    db_path = r"D:\Users\c19471\Desktop\tianeye\database\test.db"
    print(db_path)

    # 初始化数据库管理器
    db_manager = SQLiteDBManager(db_path)
    if db_manager.connect():
        try:
            # 读取数据到 DataFrame
            df = pd.read_sql_query('SELECT * FROM ip_config', db_manager.conn)
            # 处理数据，假设这里有 30 条线
            for i in range(len(df)):
                print(f"正在处理第 {i} 行...")
                try:
                    id_value = df["id"][i]
                    size=df["size"][i]
                    active_line_grade = df["active_line_grade"][i]
                    enabled = df["enabled"][i]
                    ip = df["ip"][i]
                    grade_path = df["grade_path"][i]
                    update_database(db_manager, id_value, size,active_line_grade, enabled, ip, grade_path)
                except Exception as e:
                    print(f"处理第 {i} 行时发生错误: {e}")
        except Exception as e:
            print(f"发生错误: {e}")
        finally:
            # 关闭数据库连接
            db_manager.close()

if __name__ == "__main__":
    main()
